package com.sencorsta.ids.core.tcp.socket.client;

import com.sencorsta.ids.core.application.Application;
import com.sencorsta.ids.core.function.SynFunction;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import io.netty.channel.ChannelHandler.Sharable;
/**
 * 回调服务器的反馈信息
 * @author ICe
 */
@Sharable
public class RpcClientChannelHandler extends ChannelInboundHandlerAdapter {

	private final RpcClientCallback callback;

	public RpcClientChannelHandler(RpcClientCallback callback) {
		this.callback = callback;
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		//Out.warn(cause.getMessage());
		Out.info("Client异常:",ctx.channel(),cause.getMessage());
		//cause.printStackTrace();
		ctx.channel().close();
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		Out.trace("Client添加:",ctx.channel());
		//Out.debug("handlerAdded : ", ctx.channel());
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		//Out.debug("handlerRemoved : ", ctx.channel());
		Out.trace("Client移除:",ctx.channel());
		callback.close(ctx.channel());
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object packet) throws Exception {
		//callback.handlePacket((Packet) msg);
		Out.trace("");
		Out.trace("Client收到消息:",ctx.channel(),packet);
		RpcMessage msg=(RpcMessage) packet;
		if (msg.msgId>0){
			SynFunction.response(msg.msgId,msg);
		}else {
			callback.messageReceive((RpcMessage) msg);
		}
	}

}